package com.urbanski.clipboard.client.action;

import java.io.IOException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ClipboardClient;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.common.message.CreateMessage;
import com.urbanski.clipboard.common.message.JoinMessage;
import com.urbanski.clipboard.common.message.Response;
import com.urbanski.util.logging.LoggingUtil;

public class JoinActionHandler extends ClientActionHandler
{
	private static final Logger LOGGER = Logger.getLogger(JoinActionHandler.class);

	private String server;
	private String session;
	private String password;

	public JoinActionHandler(String[] tokens)
	{
		super(ClientCommand.JOIN, tokens);
	}

	@Override
	public void execute()
	{
		processArgs();

		if (server != null && session != null)
		{
			ServerConnection serverConnection = ClipboardClient.findConnection(server);
			if (serverConnection == null)
			{
				LoggingUtil.logAndPrintError(LOGGER, "No active connection with name " + server);
			}
			else
			{
				JoinMessage message = new JoinMessage(session, password);
				Response response;
				try
				{
					response = serverConnection.sendMessage(message);
					LoggingUtil.logAndPrintInfo(LOGGER, response.getResponseText());
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	private void processArgs()
	{
		if (tokens.length != 3 && tokens.length != 4)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Invalid number of arguments for join command");
			return;
		}

		server = tokens[1];
		session = tokens[2];

		if (tokens.length == 4)
		{
			password = tokens[3];
		}
	}

}
